/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * PainelArquivo.java
 *
 * Created on 25/05/2011, 00:28:11
 */
package projeto.view;
import projeto.model.LeituraDeDados;
import javax.swing.*;
import java.io.File;
import projeto.controller.ControleBancoDeDados;
import projeto.controller.ControleDeUsuarios;
/**
 *
 * @author Javatar
 */
public class PainelArquivo extends javax.swing.JPanel {
    private static File arquivoUsuarios,arquivoEstabelecimentos;
    private boolean seraOnline = false;
    /** Creates new form PainelArquivo */
    public PainelArquivo() {
        if(!ControleBancoDeDados.verificaConexao()){
            jCheckBox1.setEnabled(false);
            jCheckBox1.setText("Usar nosso repositório online(Erro ao se comunicar com o Banco de Dados)");
        }
        initComponents();
        
        arquivoUsuarios = null;
        
    }
    
    public static File getArquivo(){
        return arquivoUsuarios;
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        botaoConfirmar = new javax.swing.JButton();
        tituloArquivoUsuarios = new javax.swing.JLabel();
        botaoAbrir1 = new javax.swing.JButton();
        textBoxArqUsuarios = new javax.swing.JTextField();
        botaoAbrir2 = new javax.swing.JButton();
        textBoxArqEsts = new javax.swing.JTextField();
        textArqUsuarios = new javax.swing.JLabel();
        textArqEsts = new javax.swing.JLabel();
        jCheckBox1 = new javax.swing.JCheckBox();

        setPreferredSize(new java.awt.Dimension(780, 550));

        botaoConfirmar.setText("Confirmar");
        botaoConfirmar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botaoConfirmarActionPerformed(evt);
            }
        });

        tituloArquivoUsuarios.setFont(new java.awt.Font("Tahoma", 1, 18));
        tituloArquivoUsuarios.setText("Arquivo de Usuários");

        botaoAbrir1.setText("Abrir");
        botaoAbrir1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botaoAbrir1ActionPerformed(evt);
            }
        });

        botaoAbrir2.setText("Abrir");
        botaoAbrir2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botaoAbrir2ActionPerformed(evt);
            }
        });

        textBoxArqEsts.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                textBoxArqEstsActionPerformed(evt);
            }
        });

        textArqUsuarios.setFont(new java.awt.Font("Tahoma", 0, 14));
        textArqUsuarios.setText("Arquivo de usuários");

        textArqEsts.setFont(new java.awt.Font("Tahoma", 0, 14));
        textArqEsts.setText("Arquivo de Estabelecimentos");

        jCheckBox1.setText("Usar nosso repositório online");
        jCheckBox1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jCheckBox1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(285, 285, 285)
                        .addComponent(tituloArquivoUsuarios))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(350, 350, 350)
                        .addComponent(botaoConfirmar))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(186, 186, 186)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(textBoxArqEsts, javax.swing.GroupLayout.PREFERRED_SIZE, 336, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(18, 18, 18)
                                .addComponent(botaoAbrir2))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(textBoxArqUsuarios, javax.swing.GroupLayout.PREFERRED_SIZE, 336, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(18, 18, 18)
                                .addComponent(botaoAbrir1))))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(272, 272, 272)
                        .addComponent(textArqEsts))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(295, 295, 295)
                        .addComponent(textArqUsuarios))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(122, 122, 122)
                        .addComponent(jCheckBox1)))
                .addContainerGap(185, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(tituloArquivoUsuarios)
                .addGap(91, 91, 91)
                .addComponent(jCheckBox1)
                .addGap(26, 26, 26)
                .addComponent(textArqUsuarios, javax.swing.GroupLayout.PREFERRED_SIZE, 17, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(botaoAbrir1)
                    .addComponent(textBoxArqUsuarios, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 48, Short.MAX_VALUE)
                .addComponent(textArqEsts)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(botaoAbrir2)
                    .addComponent(textBoxArqEsts, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(65, 65, 65)
                .addComponent(botaoConfirmar)
                .addGap(149, 149, 149))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void botaoConfirmarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botaoConfirmarActionPerformed
      if(!seraOnline){
        if(arquivoUsuarios == null || textBoxArqUsuarios.getText().equals("") || arquivoEstabelecimentos == null || textBoxArqEsts.equals("")){
                JOptionPane.showMessageDialog(null,"Algum arquivo não foi selecionado. Por favor, selecione os arquivos!","Erro", JOptionPane.ERROR_MESSAGE);
                FramePrincipal.removePainelJTabbedPane1();
            }else if(!LeituraDeDados.isArquivoUserValid(textBoxArqUsuarios.getText())){
                JOptionPane.showMessageDialog(null,"Arquivo de usuários Invalido. Por favor, selecione um arquivo valido!","Erro", JOptionPane.ERROR_MESSAGE); 
                FramePrincipal.removePainelJTabbedPane1();
            }else if(!LeituraDeDados.isArquivoEstValid(textBoxArqEsts.getText())){
                 JOptionPane.showMessageDialog(null,"Arquivo de estabelecimentos Invalido. Por favor, selecione um arquivo valido!","Erro", JOptionPane.ERROR_MESSAGE); 
                 FramePrincipal.removePainelJTabbedPane1();
            }else{
                JOptionPane.showMessageDialog(null,"Arquivo selecionado!","OK", JOptionPane.PLAIN_MESSAGE);
                FramePrincipal.setUserControl(ControleDeUsuarios.getInstance(textBoxArqUsuarios.getText()));
                FramePrincipal.criaEstabelecimentos(textBoxArqEsts.getText());
            }
      }
      else{
          if(ControleBancoDeDados.geraArquivoUsuariosLocal() && ControleBancoDeDados.geraArquivoEstabelecimentosLocal()){
             if(!LeituraDeDados.isArquivoUserValid("tempLocalFileUsuarios.data")){
                 JOptionPane.showMessageDialog(null,"Arquivo de usuários inválido, tente novamente!","Erro", JOptionPane.ERROR_MESSAGE); 
                 FramePrincipal.removePainelJTabbedPane1();
             }else if(!LeituraDeDados.isArquivoEstValid("tempLocalFileEstabelecimentos.data")){
                 JOptionPane.showMessageDialog(null,"Arquivo de estabelecimentos inválido, tente novamente!","Erro", JOptionPane.ERROR_MESSAGE); 
                 FramePrincipal.removePainelJTabbedPane1();
             }else{
                 JOptionPane.showMessageDialog(null,"Arquivo selecionado!","OK", JOptionPane.PLAIN_MESSAGE);
                 FramePrincipal.setUserControl(ControleDeUsuarios.getInstance("tempLocalFileUsuarios.data"));
                 FramePrincipal.criaEstabelecimentos("tempLocalFileEstabelecimentos.data");
                 ControleBancoDeDados.apagaArquivosTemporarios();
             }
          }else{
                   JOptionPane.showMessageDialog(null,"Não foi possivel baixar os arquivos do nosso servidor!","Erro", JOptionPane.ERROR_MESSAGE); 
                 FramePrincipal.removePainelJTabbedPane1();
          }
      }
    }//GEN-LAST:event_botaoConfirmarActionPerformed

    private void botaoAbrir1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botaoAbrir1ActionPerformed
     
       JFileChooser chooser = new JFileChooser(System.getProperty("user.dir"));
       chooser.setFileFilter(new javax.swing.filechooser.FileFilter(){  
            @Override
       public boolean accept(File f){ 
          return (f.getName().endsWith(".data")) || f.isDirectory();  
       }  
            @Override
       public String getDescription(){  
           return "*.data";  
       }  
    });
        int res = chooser.showOpenDialog(null);
        
        if(res == JFileChooser.APPROVE_OPTION){
           arquivoUsuarios = chooser.getSelectedFile();
            textBoxArqUsuarios.setText(arquivoUsuarios.getAbsolutePath());
        }
    }//GEN-LAST:event_botaoAbrir1ActionPerformed

    private void botaoAbrir2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botaoAbrir2ActionPerformed
        JFileChooser chooser = new JFileChooser(System.getProperty("user.dir"));
        chooser.setFileFilter(new javax.swing.filechooser.FileFilter(){  
            @Override
       public boolean accept(File f){ 
          return (f.getName().endsWith(".data")) || f.isDirectory();  
       }  
            @Override
       public String getDescription(){  
           return "*.data";  
       }  
    });
        int res = chooser.showOpenDialog(null);
        
        if(res == JFileChooser.APPROVE_OPTION){
           arquivoEstabelecimentos = chooser.getSelectedFile();
            textBoxArqEsts.setText(arquivoEstabelecimentos.getAbsolutePath());
        }
    }//GEN-LAST:event_botaoAbrir2ActionPerformed

    private void textBoxArqEstsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_textBoxArqEstsActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_textBoxArqEstsActionPerformed

    private void jCheckBox1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jCheckBox1ActionPerformed
        seraOnline = !seraOnline;
        FramePrincipal.isOnline = !FramePrincipal.isOnline; 
        textArqUsuarios.setEnabled(!seraOnline);
        textArqEsts.setEnabled(!seraOnline);
        botaoAbrir1.setEnabled(!seraOnline);
        botaoAbrir2.setEnabled(!seraOnline);
    }//GEN-LAST:event_jCheckBox1ActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton botaoAbrir1;
    private javax.swing.JButton botaoAbrir2;
    private javax.swing.JButton botaoConfirmar;
    private javax.swing.JCheckBox jCheckBox1;
    private javax.swing.JLabel textArqEsts;
    private javax.swing.JLabel textArqUsuarios;
    private javax.swing.JTextField textBoxArqEsts;
    private javax.swing.JTextField textBoxArqUsuarios;
    private javax.swing.JLabel tituloArquivoUsuarios;
    // End of variables declaration//GEN-END:variables
}
